<template>
    <div>
        <div>
            新闻资讯
        </div>
        <el-upload
                ref="imgBroadcastUpload"
                :auto-upload="false" multiple
                :file-list="diaLogForm.imgBroadcastList"
                list-type="picture-card"
                :on-change="imgBroadcastChange"
                :on-remove="imgBroadcastRemove"
                accept="image/jpg,image/png,image/jpeg"
                action="">
            <i class="el-icon-plus"></i>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过2M</div>
        </el-upload>
        <el-button @click="jiaogong()">submitData</el-button>
        <div>
            <img :src="hhh">
        </div>
    </div>
</template>

<script>
    import { uploadImgToBase64 } from '@/util/utils' // 导入本地图片转base64的方法

    export default {
        name: 'imgUpload',
        data () {
            return {
                goodsName:'', // 商品名称字段
                diaLogForm: {
                    imgBroadcastList:[], // 储存选中的图片列表
                    imgsStr:''   // 后端需要的多张图base64字符串 , 分割
                },
                hhh:""
            }
        },
        methods: {
            // 图片选择后 保存在 diaLogForm.imgBroadcastList 对象中
            imgBroadcastChange (file, fileList) {
                const isLt2M = file.size / 1024 / 1024 < 2 // 上传头像图片大小不能超过 2MB
                if (!isLt2M) {
                    this.diaLogForm.imgBroadcastList = fileList.filter(v => v.uid !== file.uid)
                    this.$message.error('图片选择失败，每张图片大小不能超过 2MB,请重新选择!')
                } else {
                    this.diaLogForm.imgBroadcastList.push(file)
                }
            },
            // 有图片移除后 触发
            imgBroadcastRemove (file, fileList) {
                this.diaLogForm.imgBroadcastList = fileList
            },
            async jiaogong(){
                const imgBroadcastListBase64 = []
                console.log('图片转base64开始...')
                // 并发 转码轮播图片list => base64
                const filePromises = this.diaLogForm.imgBroadcastList.map(async file => {
                    const response = await uploadImgToBase64(file.raw)
                    console.log("图片转吗",response)
                    return response.result//.replace(/.*;base64,/, '') // 去掉data:image/jpeg;base64,
                })
                for (const textPromise of filePromises) {
                    imgBroadcastListBase64.push(await textPromise)
                }
                console.log('图片转base64结束..., ', imgBroadcastListBase64)
                this.diaLogForm.imgsStr = imgBroadcastListBase64.join()
                console.log(this.diaLogForm)
                console.log(filePromises)
                const {data: res} = await this.$http.post("newstupian", this.diaLogForm);
                this.hhh=res.hh
                console.log(res.hh)
                }
        }
    }
</script>